import {ref} from "vue";
import {fetchPhoneNum} from "../../api/auth";
export function usePhoneNum(){

    const phoneNum = ref('')
    async function getPhoneNum(e: any) {

        const {encryptedData, iv, errMsg} = e.detail
        if (errMsg !== 'getPhoneNumber:ok'){
            return
        }

        try {
            await uni.checkSession({})

        }catch (err){

        }finally {
            await uni.login({
                provider: 'weixin'
            })
        }

        // @ts-ignore
        const {code} = await uni.login({
            provider: 'weixin'
        })

        const res = await fetchPhoneNum({
            js_code: code,
            encryptedData,
            iv
        })
        // console.log('req: ',{code,encryptedData,iv})
        if (res.error !== 'content'){
            uni.showToast({
                icon: 'error',
                title: '获取手机号失败'
            })
        }else {
            // phoneNum.value = res.RES.phoneNumber
			//倒序解密的手机号
			const yz_decode =hexStringToPhoneNumber(res.RES.phoneNumber_yz);
			//正序解密的手机号
			const asc_decode =hexStringToPhoneNumber(res.RES.phoneNumber);
			// console.log(yz_decode,asc_decode,"sssssssssssss");
			//判断手机号是否相等 且 首位等于1 ,否则报错
			if(comparePhoneNumbers(yz_decode,asc_decode)&&asc_decode[0] == '1'){
				phoneNum.value=asc_decode;
			
			}else{
				uni.showToast({
					title:"数据异常，重新获取",
					icon:"none",
					duration:2000
				})
			}
		}
    }
	// 解密 16进制->10进制->Ascii->手机号
	function hexStringToPhoneNumber(hexString: string): string {
	  // 将16进制字符串转换为10进制字符串
	  const decimalString = BigInt(`0x${hexString}`).toString();
	  // 将10进制字符串按照ASCII码转换为字符
	  let phoneNumber = '';
	  for (let i = 0; i < decimalString.length; i += 2) {
	    const asciiCode = parseInt(decimalString.substr(i, 2));
	    phoneNumber += String.fromCharCode(asciiCode);
	  }
	  return phoneNumber;
	}
	
	//手机号正序和倒序比较
	function comparePhoneNumbers(phoneNumber1: string, phoneNumber2: string): boolean {
	  return phoneNumber1 === phoneNumber2.split('').reverse().join('');
	}

    return {
        phoneNum,
        getPhoneNum
    }
}
